package com.platform.manager.action.system;

import com.platform.common.mybatis.Page;
import com.platform.common.mybatis.context.ContextHolder;
import com.platform.common.util.JsonUtil;
import com.platform.common.util.StringUtil;
import com.platform.domain.model.Function;
import com.platform.domain.model.FunctionExpand;
import com.platform.domain.model.Role;
import com.platform.domain.result.DataGirdData;
import com.platform.domain.result.ResultData;
import com.platform.domain.result.TreeData;
import com.platform.domain.result.TreeGridData;
import com.platform.manager.action.BaseAction;
import com.platform.service.FunctionService;
import org.apache.struts2.convention.annotation.*;
import org.apache.struts2.json.annotations.JSON;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: wangyanginfo
 * Date: 12-9-18
 * Time: 下午2:34
 * To change this template use File | Settings | File Templates.
 */
@Namespace("/system")
@Service("functionAction")
@ParentPackage("jsonPackage")
public class FunctionAction extends BaseAction {

    @Resource
    private FunctionService functionService;

    private List<FunctionExpand> functionExpands;

    private List<FunctionExpand> functions;

    private FunctionExpand function;

    /**
     * 查询功能信息列表
     *
     * @return
     */
    @Action(value = "queryFunctions", interceptorRefs = @InterceptorRef("pageStack"),
            results = {@Result(name = "success", type = "json", params = {"root", "dataGirdData"})})
    public String queryFunctions() {
        try {
            // 查询符合条件的用户列表
            List<Function> list = functionService.select(null);
            dataGirdData = new DataGirdData();
            dataGirdData.setRows(list);
            // 获取翻页参数
            Page page = ContextHolder.getPage();
            dataGirdData.setTotal(page.getTotalResult());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return SUCCESS;
    }

    /**
     * 保存功能信息列表
     *
     * @return
     */
    @Action(value = "saveFunctions", results = {@Result(name = "success", type = "json", params = {"root", "result"})})
    public String saveFunctions() {
        try {
            if (jsonStr != null) {
                print("前台发送的JSON数据：" + jsonStr);
                Map<String, List> maps = JsonUtil.jsonToMap(jsonStr, Function.class);
                List inserted = maps.get("inserted");
                List updated = maps.get("updated");
                List deleted = maps.get("deleted");

                // 保存未插入、更新、删除成功的的用户登录名
                StringBuffer buffer = new StringBuffer();

                if (inserted != null) {
                    for(Object obj : inserted){
                        Function fun = (Function) obj;
                        int resInt = functionService.insert(fun);
                        if (resInt != 1) {
                            buffer.append(" [").append(fun.getFunctionId()).append("]");
                        }
                    }
                }

                if (updated != null) {
                    for(Object obj : updated){
                        Function fun = (Function) obj;
                        int resInt = functionService.update(fun);
                        if (resInt != 1) {
                            buffer.append(" [").append(fun.getFunctionId()).append("]");
                        }
                    }
                }

                if (deleted != null) {
                    for(Object obj : deleted){
                        Function fun = (Function) obj;
                        int resInt = functionService.delete(fun);
                        if (resInt != 1) {
                            buffer.append(" [").append(fun.getFunctionId()).append("]");
                        }
                    }
                }


                result = new ResultData();
                if (buffer.length() == 0) {
                    result.setSuccess(true);
                    result.setMessage("操作成功！");
                } else {
                    result.setSuccess(false);
                    result.setMessage("操作失败！\n以下功能操作失败！\n[功能ID]：" + buffer.toString());
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return SUCCESS;
    }

    /**
     * 查询用户角色权限列表
     *
     * @return
     */
    @Action(value = "queryRoleFunctions", results = {@Result(name = "success", type = "json", params = {"root", "datas"})})
    public String queryRoleFunctions() {
        try {
            // 查询符合条件的记录总数
            functions = functionService.selectMenuByRoleId(function.getRoleId());

            if (functions != null) {
                treeGridDatas = new ArrayList<TreeGridData>();
                for (Function fun : functions) {
                    TreeGridData data = new TreeGridData();
                    data.setId(fun.getFunctionId());
                    data.setText(fun.getFunctionName());
                    treeGridDatas.add(data);
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return SUCCESS;
    }

    /**
     * 查询权限列表
     *
     * @return
     */
    @Action(value = "queryTreeFunction", results = {@Result(name = "success", type = "json", params = {"root", "treeDatas"})})
    public String queryTreeFunction() {
        try {
            TreeData treeData = new TreeData();
            // 查询顶层功能集合
            Map<String, String> params = new HashMap<String, String>();
            params.put("joinRoleId", function.getRoleId());

            boolean isSuperior = function == null
                    || function.getFunSuperior() == null
                    || function.getFunSuperior().trim().length() < 1;

            if (isSuperior) {
                params.put("isRoot", "true");
                treeData.setId("-1");
                treeData.setText("权限列表");
            } else {
                params.put("funSuperior", function.getFunSuperior());
            }

            treeData.setChildren(new ArrayList<TreeData>());

            functionExpands = functionService.selectFunctions(params);

            if (functionExpands != null) {
                for (FunctionExpand fun : functionExpands) {
                    TreeData data = new TreeData();
                    data.setId(fun.getFunctionId());
                    data.setText(fun.getFunctionName());
                    data.setChecked(StringUtil.isNotBlank(fun.getRoleId()) ? true : false);
                    data.setState(fun.getChildNum() > 0 ? TreeData.STATE_CLOSED : TreeData.STATE_OPEN);
                    String[] strs = new String[1];
                    strs[0] = "funSuperior:" + fun.getFunSuperior();
                    data.setAttributes(strs);
                    treeData.getChildren().add(data);
                }
            }

            if (isSuperior) {
                treeDatas = new ArrayList<TreeData>();
                treeDatas.add(treeData);
            } else {
                treeDatas = treeData.getChildren();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return SUCCESS;
    }

    /**
     * 查询权限列表
     *
     * @return
     */
    @Action(value = "queryAllTreeFunction", results = {@Result(name = "success", type = "json", params = {"root", "treeDatas"})})
    public String queryAllTreeFunction() {
        try {
            TreeData treeData = new TreeData();
            // 查询顶层功能集合
            Map<String, String> params = new HashMap<String, String>();
            params.put("joinRoleId", function.getRoleId());

            treeData.setId("-1");
            treeData.setText("权限列表");

            treeData.setChildren(new ArrayList<TreeData>());

            functionExpands = functionService.selectFunctions(params);

            if (functionExpands != null) {
                for (FunctionExpand fun : functionExpands) {
                    TreeData data = new TreeData();
                    data.setId(fun.getFunctionId());
                    data.setText(fun.getFunctionName());
                    data.setState(fun.getChildNum() > 0 ? TreeData.STATE_CLOSED : TreeData.STATE_OPEN);

                    if (fun.getFunSuperior() == null || fun.getFunSuperior().trim().length() < 1) {
                        treeData.getChildren().add(data);
                    } else {
                        data.setChecked(StringUtil.isNotBlank(fun.getRoleId()) ? true : false);
                        String funSup = fun.getFunSuperior();
                        for (TreeData temp : treeData.getChildren()) {
                            if (funSup.equals(temp.getId())) {
                                if (temp.getChildren() != null) {
                                    temp.getChildren().add(data);
                                } else {
                                    List<TreeData> temps = new ArrayList<TreeData>();
                                    temps.add(data);
                                    temp.setChildren(temps);
                                }
                            }
                        }
                    }
                }
            }

            treeDatas = new ArrayList<TreeData>();
            treeDatas.add(treeData);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return SUCCESS;
    }

    @JSON
    public List<FunctionExpand> getFunctionExpands() {
        return functionExpands;
    }

    public void setFunctionExpands(List<FunctionExpand> functionExpands) {
        this.functionExpands = functionExpands;
    }

    @JSON
    public List<FunctionExpand> getFunctions() {
        return functions;
    }

    public void setFunctions(List<FunctionExpand> functions) {
        this.functions = functions;
    }

    public FunctionExpand getFunction() {
        return function;
    }

    public void setFunction(FunctionExpand function) {
        this.function = function;
    }
}
